import api from "@/api/index.js";
import reportApi from '@/api/modules/report'
import {getQueryString, getRequestParam} from "@/utils/index.js";
import AuthInfo from "@/utils/authInfo.js";

export async function checkMapping() {
  try {
    let deptId = getQueryString("deptId");
    console.log("window.location.href.includes('webIndex')",window.location.href,window.location.href.includes('webIndex'))
    uni.setStorageSync("href", window.location.href);
    uni.setStorageSync("webIndex", window.location.href.includes('webIndex'));
    if (window.location.href.includes('webIndex') || window.location.href.includes('open.weixin.qq.com')) return
    if (deptId) {
      // 先检查是否存在部门映射
      const res = await api.deptMapping.getMapping();
      if (res && res.code === 200 && res.data) {
        const targetDeptId = res.data.targetDeptId
        if (targetDeptId) {
          let newHref = `${window.location.origin}${window.location.pathname}?deptId=${targetDeptId}`
          const reqParam = getRequestParam()
          if (reqParam) {
            Reflect.deleteProperty(reqParam, 'deptId')
            const paramKeys = Object.keys(reqParam);
            if (paramKeys && paramKeys.length > 0) {
              for (let i = 0; i < paramKeys.length; i++) {
                newHref+=`&${paramKeys[i]}=${reqParam[paramKeys[i]]}`
              }
            }
          }
          uni.setStorageSync("errorInfo1", newHref);

          window.location.href = newHref
        }
        return
      }
      AuthInfo.toAuth()
    }
  } catch (e) {
    console.log('catch==>',e)
    try {
      let text = '部门Mapping错误 ' + ' \n '
      text += ` ex: ${e}  \n `
      text += ` stack: ${e.stack} \n`
      let deptId = getQueryString("deptId")
      await reportApi.errorReport({error: text, appId: '', openId: '', deptId});
    } catch (e) {
      console.log(e)
    }

    uni.setStorageSync("errorInfo2", 'catch'+e);

    AuthInfo.toAuth()
  }
}
